# -*- coding: utf-8 -*-
from datetime import timedelta

from odoo import models, fields, api
from odoo.exceptions import ValidationError, UserError


class EmployeeCalendarPeriod(models.Model):
    """
    排班表
    """
    _name = 'employee.calendar.period'
    _rec_name = 'employee_id'
    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin']
    _order = 'create_date desc'
    employee_id = fields.Many2one('hr.employee', string='员工', required=True, index=True, track_visibility='onchange')
    barcode = fields.Char(related='employee_id.barcode', string='工号')
    department_id = fields.Many2one('hr.department', string=u'部门', related='employee_id.department_id', store=True)

    @api.onchange('department_id')
    def onchange_department(self):
        if self.employee_id:
            self.department_id = self.employee_id.department_id

    date_start = fields.Date(string='开始日期', track_visibility='onchange')
    date_end = fields.Date(string='截止日期', track_visibility='onchange')

    # @api.depends('date_start', 'calendar_id')
    # def compute_date_end_real(self):
    #     for record in self:
    #         if record.calendar_id.calendar_type == '3':
    #             record.date_end_real = record.date_end + timedelta(days=1)
    #         else:
    #             record.date_end_real = record.date_end
    #
    # date_end_real = fields.Date(string='截止日期', compute='compute_date_end_real',store=True,index=True)
    calendar_id = fields.Many2one('resource.calendar', string=u'班别', index=True, track_visibility='onchange')
    date = fields.Datetime(index=True)
    active = fields.Boolean(default=True)

    @api.constrains('date_start', 'date_end')
    def check_dates(self):
        for r in self:
            if r.date_start > r.date_end:
                raise ValidationError('开始时间不能大于结束时间')

    def write(self, vals):
        if 'calendar_id' in vals and self.calendar_id.id!=vals['calendar_id']:
            sheet_ids=self.env['hr.overtime'].search([('employee_id','=',self.employee_id.id),('apply_date','>=',self.date_start),('apply_date','<=',self.date_end)])
            names=[]
            for s in sheet_ids:
                names.append(s.sheet_id.name)
            if names:
                mssage=';'.join(names)
            raise UserError('已经有加班单存在不可以修改班别,加班单号'+mssage)

        return super(EmployeeCalendarPeriod, self).write(vals)

    # def write(self, vals):
    #     for record in self:
    #         start_p=0
    #         end_p=0
    #         if 'date_start' in vals:
    #             start_p = self.env[self._name].search(
    #                 [('employee_id', '=', self.employee_id.id), ('date_start', '<=',vals['date_start']),
    #                  ('date_end', '>=', vals['date_start'])])
    #         if 'date_end' in vals:
    #             end_p = self.env[self._name].search(
    #                 [('employee_id', '=', self.employee_id.id),  ('date_start', '<=', vals['date_end']),
    #                  ('date_end', '>=', vals['date_end'])])
    #         if start_p and start_p!=self:
    #             raise UserError('%s 已经有对应排班，不可以重复创建' % vals['date_start'])
    #         if end_p and start_p!=self:
    #             raise UserError('%s 已经有对应排班，不可以重复创建' % vals['date_end'])
    #         # overtime=self.env['hr.overtime'].sudo().search([('state','!=','draft'),('employee_id','=',record.employee_id.id),'|',('apply_date','>=',record.date_start),('apply_date','>=',record.date_end)])
    #         # if overtime:
    #         #     raise UserError('已经有加班单存在,不允许修改')
    #     res=super(EmployeeCalendarPeriod, self).write(vals)
    #     return res
    @api.model
    def create(self, vals):
        start_p = self.env[self._name].search(
            [('employee_id', '=', vals['employee_id']), ('date_start', '<=', vals['date_start']),
             ('date_end', '>=', vals['date_start'])])
        end_p = self.env[self._name].search(
            [('employee_id', '=', vals['employee_id']), ('date_start', '<=', vals['date_end']),
             ('date_end', '>=', vals['date_end'])])
        if start_p:
            raise UserError('%s 已经有对应排班，不可以重复创建' % vals['date_start'])
        if end_p:
            raise UserError('%s 已经有对应排班，不可以重复创建' % vals['date_end'])
        res = super(EmployeeCalendarPeriod, self).create(vals)

        return res
